package v1

import (
	"encoding/json"
	"errors"
	"gin-study/app/http/responses"
	"gin-study/app/services"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"sync"
)

var UserCenter = new(userCenter)

type userCenter struct {
	controller
}

func (this *userCenter) Index(c *gin.Context) interface{} {
	user, err := services.User.GetUserById(services.Ctx.GetUser(c).ID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return responses.NotFind("找不到这个会员", nil)
	}
	if err != nil {
		return responses.ServerError(err.Error(), nil)
	}
	return responses.Ok("ok", gin.H{
		"user": user,
	})
}

func (this *userCenter) Get(c *gin.Context) interface{} {

	var users []interface{}

	wg := &sync.WaitGroup{}
	wg.Add(2)

	fn := func(id string) {
		req, _ := http.NewRequest("GET", "http://127.0.0.1:8199/v1/users/"+id, nil)
		req.Header.Set("Authorization", "Bearer 1")
		res, _ := http.DefaultClient.Do(req)
		defer res.Body.Close()
		var user map[string]map[string]interface{}
		json.NewDecoder(res.Body).Decode(&user)
		users = append(users, user["data"]["user"])
		wg.Done()
	}

	go fn("1")
	go fn("2")
	wg.Wait()

	return responses.Ok("", gin.H{
		"users": users,
	})
}

func (this *userCenter) Post(c *gin.Context) interface{} {
	return responses.NotFind("404", nil)
}

func (this *userCenter) Put(c *gin.Context) interface{} {
	return responses.NotFind("404", nil)
}

func (this *userCenter) Delete(c *gin.Context) interface{} {
	return responses.NotFind("404", nil)
}
